<?php
class Application_Model_Base_Memory_CheckArguments
{
	public static function checkArg($arguments, $value)
	{
		$arg = array();

		foreach ($arguments as $key => $condition)
		{
			if(is_array($condition))
			{
				$a = self::_checkOneCondition($value, $condition);

				if($a == true)
				{
					$arg[$key] = 1;
				}
				else
				{
					$arg[$key] = -1;
				}
			}
			else
			{
				$arg[$key] = $condition;
			}
		}
		return self::_preCheckArg($arg);
	}
	
	private static function _preCheckArg($arg)
	{
		if(intval($arg[0]) != 0)
		{
			return intval($arg[0]) == 1;
		}
		else
		{
			$i = count($arg) - 1;

			while (intval($arg[$i]) != 0)
			{
				$i = $i - 1;
			}

			if($arg[$i]=="|")
			{
				$arg[$i+1] = self::_covertIntToBool($arg[$i+1]);

				$arg[$i+2] = self::_covertIntToBool($arg[$i+2]);

				$arg[$i] = $arg[$i+1] || $arg[$i+2];

				$arg[$i] = self::_coverBoolToInt($arg[$i]);
			}
			else
			{
				$arg[$i+1] = self::_covertIntToBool($arg[$i+1]);

				$arg[$i+2] = self::_covertIntToBool($arg[$i+2]);

				$arg[$i] = $arg[$i+1] && $arg[$i+2];

				$arg[$i] = self::_coverBoolToInt($arg[$i]);
			}
			
			for($j = $i+1; $j < count($arg) - 2;$j++)
			{
				$arg[$j] = $arg[$j+2];
			}

			unset($arg[count($arg) - 1]);

			unset($arg[count($arg) - 1]);

			return self::_preCheckArg($arg);
		}
	}

	public static function _checkOneCondition($value, $condition)
	{
		$op = $condition[1];
		$cmpValue = $condition[2];
		$field = $condition[0];

		switch($op)
		{
			case "like":
			case "Like":
			case "LIKE":
				return Application_Model_Base_Memory_CheckCondition::
					likeCondition($cmpValue, $value[$field]);
				break;

			case "in":
			case "IN":
			case "In":
				return Application_Model_Base_Memory_CheckCondition::
					inCondition($cmpValue, $value[$field]);
				break;

			default:
				$cmpField = "'{$value[$field]}'";
				$cmpValue = "'{$cmpValue}'";
				eval('$run = '.$cmpField.$op.$cmpValue.';');
				return $run;
				break;
		}
	}
	
	private static function _covertIntToBool($a)
	{
		if ($a == -1)
		{
			return 0;
		}
		else
		{
			return a;
		}
	}
	private static function _coverBoolToInt($a)
	{
		if ($a == true)
		{
			return 1;
		}
		else
		{
			return -1;
		}
	}
}